package ar.republicagroup.gestion.view;

import ar.republicagroup.gestion.entities.CalendarioBancario;
import ar.republicagroup.gestion.services.CalendarioBancarioServices;
import ar.republicagroup.gestion.util.SpringUtils;
import ar.republicagroup.gestion.util.helpers.Formato;
import ar.republicagroup.gestion.util.helpers.UserInterfaceHelper;
import ar.republicagroup.gestion.util.messages.UIMessages;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import javax.swing.JOptionPane;
import org.apache.log4j.Logger;

/**
 *
 * @author DIEGOALV
 */
public class frmCalendario extends javax.swing.JDialog {

    /* Services */
    CalendarioBancarioServices calendarioBancarioServices = (CalendarioBancarioServices)SpringUtils.getBean("calendarioBancarioServices");
    Logger log = Logger.getLogger(frmCalendario.class);
    Calendar fechaSeleccionada;
    /* Listados */
    Set<CalendarioBancario> calendarioSet = new HashSet<>();
    

    public frmCalendario(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        cargarDatos();
    }

    
    private void cargarDatos(){
        Locale local = new Locale("es", "US");
        jCalendar.setLocale(local);
        calendarioSet = calendarioBancarioServices.findEntities();
        UserInterfaceHelper.drawHolidaysOnThisCalendar(jCalendar, calendarioSet);
    }
    
    
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jCalendar = new com.toedter.calendar.JCalendar();
        txtFecha = new javax.swing.JTextField();
        txtMotivoFeriado = new javax.swing.JTextField();
        btnAdd = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        btnEliminar = new javax.swing.JButton();

        jButton1.setText("Es feriado");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Calendario");

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Seleccione una fecha"));

        jCalendar.setWeekOfYearVisible(false);
        jCalendar.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                jCalendarPropertyChange(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jCalendar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jCalendar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        txtFecha.setEditable(false);

        btnAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/add.png"))); // NOI18N
        btnAdd.setText("Agregar");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        jLabel1.setText("Fecha");

        jLabel2.setText("Motivo del feriado");

        btnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/delete.png"))); // NOI18N
        btnEliminar.setText("Eliminar");
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtMotivoFeriado, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btnAdd)
                        .addGap(18, 18, 18)
                        .addComponent(btnEliminar)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(17, 17, 17)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel2)
                        .addGap(4, 4, 4)
                        .addComponent(txtMotivoFeriado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnAdd)
                            .addComponent(btnEliminar))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jCalendarPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jCalendarPropertyChange

        if ("calendar".equals(evt.getPropertyName())) {
            System.out.println(evt.getPropertyName()
                + ": " + (Calendar) evt.getNewValue());
            fechaSeleccionada = (Calendar)evt.getNewValue();
            mostrarFecha(fechaSeleccionada);
            UserInterfaceHelper.drawHolidaysOnThisCalendar(jCalendar, calendarioSet);
        }

    }//GEN-LAST:event_jCalendarPropertyChange

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        if(! txtFecha.getText().isEmpty()){
            CalendarioBancario nuevoFeriado = new CalendarioBancario();
            nuevoFeriado.setFechaFeriado(fechaSeleccionada.getTime());
            nuevoFeriado.setMotivo(txtMotivoFeriado.getText());
            nuevoFeriado.setVigente(true);
            String mensaje = calendarioBancarioServices.insert(nuevoFeriado);
        
            if(mensaje != null){
                    JOptionPane.showMessageDialog(this, mensaje, UIMessages.getInfoMessage("onCompleteInsert_title"), JOptionPane.INFORMATION_MESSAGE);
                    limpiarDatos();
                }
            cargarDatos();
        }else{
            JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("noDateSelected"), UIMessages.getErrorMessage("defaultErrorTitle"), JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btnAddActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        
        if(! txtFecha.getText().isEmpty()){
            String mensaje = null;
            Date fechita =  fechaSeleccionada.getTime();
            fechita.setHours(0);
            fechita.setMinutes(0);
            fechita.setSeconds(0);

            for(CalendarioBancario fecha : calendarioSet){
                if((fechita.getMonth() == fecha.getFechaFeriado().getMonth() && (fechita.getDate() == fecha.getFechaFeriado().getDate()))){
                    fecha.setVigente(false);
                    mensaje = calendarioBancarioServices.delete(fecha);
                    break;
                }
            }

            if(mensaje != null){
                JOptionPane.showMessageDialog(this, UIMessages.getInfoMessage("onDeleteFeriado"), UIMessages.getInfoMessage("defaultInfoTitle"), JOptionPane.INFORMATION_MESSAGE);
            }else{
                JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("onDeleteError"), UIMessages.getErrorMessage("defaultErrorTile"), JOptionPane.ERROR_MESSAGE);
            }

            limpiarDatos();
            cargarDatos();
        
        } else {
            JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("noDateSelected"), UIMessages.getErrorMessage("defaultErrorTitle"), JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btnEliminarActionPerformed
   public void mostrarFecha(Calendar fechaSeleccionada){
       txtFecha.setText(Formato.fechaDDMMYY(fechaSeleccionada.getTime()));    
   } 
    
   public void limpiarDatos(){
       txtFecha.setText("");
       txtMotivoFeriado.setText("");
   } 
    
   
   
    
    public static void main(String args[]) {
       
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                frmCalendario dialog = new frmCalendario(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton jButton1;
    private com.toedter.calendar.JCalendar jCalendar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTextField txtFecha;
    private javax.swing.JTextField txtMotivoFeriado;
    // End of variables declaration//GEN-END:variables
}
